package farmaciaweb.com.br.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import farmaciaweb.com.br.dao.TransportadoraDAO;
import farmaciaweb.com.br.entity.Transportadora;
import farmaciaweb.com.br.util.JPAUtil;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@PersistenceContext(unitName = "FarmaciaWebJPA")
public class TransportadoraDAOImpl implements TransportadoraDAO{

	private static final long serialVersionUID = -6482561517277429123L;
	
	private EntityManager em;
		
	@Override
	public Transportadora saveAtomic(Transportadora transportadora) {
		Transportadora transportadoraSalva = null;
		
		try{
			this.em = JPAUtil.getEntityManger();
			this.em.getTransaction().begin();
			transportadoraSalva = this.em.merge(transportadora);
			this.em.getTransaction().commit();
			this.em.close();
		}
		catch(Exception e){
			return null;
		}	
		
		return transportadoraSalva;	
	}
	
	@Override
	public void deleteAtomic(Transportadora transp) {
		
		try{
			this.em = JPAUtil.getEntityManger();
			this.em.getTransaction().begin();
			this.em.remove(transp);
			this.em.getTransaction().commit();
			this.em.close();
		}
		catch(Exception e){
			e.getStackTrace();
		}	
		
	}

	
	public List<Transportadora> pesquisarTransportadora(String nome, String cnpj){
		Map<String, Object> listaParams;
		listaParams = new HashMap<String, Object>();
		listaParams.put("nome", nome);
		listaParams.put("cnpj", cnpj);		
		return JPAUtil.findByNamedQueryAndNamedParams("bd_farmaciaweb.consultaTransportadora", listaParams);
	}
	
	public Transportadora findById(int id){
		Transportadora t = new Transportadora();
		t = em.find(Transportadora.class, id);
		return t;
	}
	
	public EntityManager getEm() {
		return em;
	}

	public void setEm(EntityManager em) {
		this.em = em;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}
}